<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrapper">
      <div class="title">
        基本信息
      </div>
      <el-form class="el-form__two" style="width:100%" :model="dataForm" ref="dataForm" label-width="200px"
        :rules="roleRules">
        <el-row>
          <el-form-item label="货品类别" prop="serverType">
            <el-select v-model="dataForm.serverType" class="readonly" :disabled="$route.query.id ? true : false">
              <el-option :value="1" label="普通">

              </el-option>
              <el-option :value="3" label="计时">

              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="货品分类" prop="classifyIds">
            <el-cascader v-model="dataForm.classifyIds" :options="treeThreeServerList"
              :props="{ label: 'classifyName', value: 'serverClassifyId' }" clearable>
            </el-cascader>
          </el-form-item>
          <el-form-item prop="name" label="货品名称:">
            <el-input type="text" v-model="dataForm.name" clearable placeholder="请输入货品名称"></el-input>
          </el-form-item>
          <el-form-item prop="dockingType" label="对接类型" v-show="dataForm.dockingFlag==2">
            <el-select v-model="dataForm.dockingType" placeholder="请选择对接类型">
                <el-option v-for="item in $Options.dockingTypeList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="businessConfirmWay" label="商户确认方式:">
            <el-select v-model="dataForm.businessConfirmWay">
              <el-option v-for="item in $Options.businessConfirmWayList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="visitFlag" label="是否上门:">
            <el-radio-group v-model="dataForm.visitFlag" @change="handleFlagChange(1)">
              <el-radio  :label="1">是</el-radio>
              <el-radio  :label="0">否</el-radio>
            </el-radio-group>

          </el-form-item>
          <el-form-item prop="shopFlag" label="是否到店:">
            <el-radio-group v-model="dataForm.shopFlag"  @change="handleFlagChange(2)">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="remoteFlag" label="是否远程:">
            <el-radio-group v-model="dataForm.remoteFlag"  @change="handleFlagChange(3)">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="dockingFlag" label="是否对接:">
            <el-radio-group v-model="dataForm.dockingFlag" @change="dataForm.dockingType=''">
              <el-radio :label="1">非对接</el-radio>
              <el-radio :label="2">对接</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="fastFlag" label="紧急通知:">
            <el-radio v-model="dataForm.fastFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.fastFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="backFlag" label="是否必须归还:" v-show="dataForm.serverType==3">
            <el-radio v-model="dataForm.backFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.backFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="specDisplayType" label="多规格单项展示方式">
            <el-radio-group v-model="dataForm.specDisplayType" :disabled="specDisplayType">
              <el-radio  :label="0">默认</el-radio>
              <el-radio  :label="1">页面展示</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="title">
        价格信息
      </div>
      <el-form :model="dataForm" class="el-form__two" ref="dataForm2" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item prop="price" label="平台原价:">
            <el-input type="number" v-model.number="dataForm.price" @input="handleMoneyInput(0)" clearable></el-input>
          </el-form-item>
          <el-form-item label="平台售价:">
            <el-input type="number" v-model.number="dataForm.salePrice" @input="handleMoneyInput(1)" clearable></el-input>
          </el-form-item>
          <el-form-item label="商户原价:" prop="marketPrice">
            <el-input type="number" v-model.number="dataForm.marketPrice" @input="handleMoneyInput(5)"
              @blur="handleMarketPriceBlur" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="discount" label="商户折扣比例:">
            <el-input style="position:relative" type="number" v-model.number="dataForm.discount"
              @blur="handleDiscountBlur" @input="handleDiscountInput" clearable>
              <span slot="suffix">%</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="costPrice" label="成本价:">
            <el-input type="number" v-model.number="dataForm.costPrice" @input="handleMoneyInput(2)" clearable></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="押金" prop="deposit" type="number" v-if="dataForm.serverType == 3">
            <el-input type="number" v-model.number="dataForm.deposit" clearable @input="handleMoneyInput(4)">
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="packageFee" label="包装费:">
            <el-input type="number" v-model.number="dataForm.packageFee" clearable
              @input="handleMoneyInput(3)"></el-input>
          </el-form-item>
          <el-form-item prop="packageFlag" label="包装费计算方式">
            <el-radio v-model="dataForm.packageFlag" :label="1">独立包装费</el-radio>
            <el-radio v-model="dataForm.packageFlag" :label="2">合并包装费</el-radio>
          </el-form-item>
          <el-form-item prop="fastFlag" label="是否需配送费:">
            <el-radio v-model="dataForm.deliveryFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.deliveryFlag" :label="0">否</el-radio>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="title">
        货品视频图片与规格
      </div>
      <el-row style="width: 96%;margin: 0 auto;">
        <div class="flex-box">
          <div class="server-img">
            <span class="label">*</span>
            货品视频图片
          </div>
          <div class="btn-wrapper">
            <el-button type="danger" size="mini" @click="showImageSelectDialog = true">复制公共图库</el-button>
          </div>
        </div>

        <UploadOssFile :list="fileList" @getImgVideo="getImgVideo" folder="serverImg"></UploadOssFile>
        <GoodsSpec
        :showStock="false"
        :mainImg="mainImg"
        ref="goodsSpec"
        :info="dataForm"
        :specList="dataForm.specs"
        :tableList="dataForm.commonServerVariants"
        folder="serverImg"
        :serverType="dataForm.serverType">
        </GoodsSpec>
      </el-row>
      <div class="title">
        商品详情描述
      </div>
      <el-row style="width: 96%;margin: 0 auto;">
        <div class="introduce">
          <div class="item">
            <div class="label">
              货品简介
            </div>
            <el-input rows="4" type="textarea" maxlength="200" show-word-limit v-model="dataForm.introduce" placeholder="请输入货品简介"></el-input>
          </div>
          <div class="item">
            <div class="label">
              备注
            </div>
            <el-input rows="4" type="textarea" v-model="dataForm.remark" placeholder="请输入备注"></el-input>
          </div>
        </div>
        <RichEditor :richText="dataForm.describes" @getRichText="getRichText"></RichEditor>
      </el-row>
      <el-row class="bottom"
        :style="{ width: !$store.getters.sidebar.opened ? 'calc(100vw - 87px)' : 'calc(100vw - 239px)' }">
        <div class="wrapper">
          <div class="back" @click="returnList">
            返回
          </div>
          <div class="save" @click="sureClick()">
            保存
          </div>
        </div>
      </el-row>
    </div>
    <ImageSelect :show="showImageSelectDialog" folder="serverImg" :limit="limitNum"
      @cancel="showImageSelectDialog = false" @getUrlList="getUrlList"></ImageSelect>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import CommonServerApi from '@/api/goods/commonServer';
import ServerClassifyApi from "@/api/server/serverClassify"
import { getStorage } from '@/utils/auth'
import { USER_INFO } from "@/constants/storeName"
import UploadImg from "../../components/UploadImg.vue";
import GoodsSpec from "../../components/GoodsSpec.vue";
import RichEditor from "../../components/RichEditor.vue";
import UploadOssFile from "../../components/UploadOssFile.vue";
import ImageSelect from "../../components/ImageSelect.vue";

export default {
  data() {
    return {
      userInfo: "",
      dataForm: {
        commonServerId: "",
        //sort:"",
        classifyIds: [],
        serverType: 1,
        deposit: "",
        name: "",
        commonServerImages: [],
        introduce: "",
        describes: "",
        businessConfirmWay:1,
        dockingFlag:1,
        dockingType:"",
        visitFlag: 1,//是否上门，1代表是
        shopFlag: 0,//是否到店，1代表是，0代表不是
        remoteFlag: 0,//是否远程，1代表是，0代表不是
        fastFlag: 0,//紧急通知
        backFlag:1,//是否必须归还 1表示是 0表示不是
        deliveryFlag: 1,//是否需配送费
        packageFlag: 1,//包装费计算方式(1.独立包装费(默认) 2.合并包装费)
        price: "",
        discount: "",
        marketPrice:"",
        salePrice: "",
        costPrice: "",
        // deliveryFee: "",
        packageFee: "",
        remark: "",
        specs: [],
        commonServerVariants: [],
        variantState: 1,
        commonServerCode: "",
        specDisplayType:0,
      },
      fileList: [],
      treeThreeServerList: [],
      loadingIns: false,
      roleRules: {
        classifyIds: [
          { required: true, message: "请选择货品分类", trigger: "change" }
        ],
        name: [
          { required: true, message: "请输入货品名称", trigger: "blur" }
        ],
        price: [
          { required: true, type: 'number', message: "请输入平台原价", trigger: "blur" }
        ],
        salePrice: [
          { required: true, type: 'number', message: "请输入平台售价", trigger: "blur" }
        ],
        costPrice: [
          { required: true, type: 'number', message: "请输入成本价", trigger: "blur" }
        ],
        discount: [
          { required: true, type: "number", message: "请输入商户折扣比例", trigger: "blur" }
        ],
        marketPrice: [
          { required: true, type: 'number', message: "请输入商户原价", trigger: "blur" }
        ],
        deposit: [
          { required: true, type: 'number', message: "请输入押金", trigger: "blur" }
        ],
      },
      showImageSelectDialog: false,
      limit: 5,
    }
  },
  computed: {
    mainImg() {
      let val = this.dataForm.commonServerImages.find(item => item.mainFlag)
      return val ? val.url : ""
    },
    limitNum() {
      return this.limit - this.dataForm.commonServerImages.length
    },
    specDisplayType(){
      if(this.dataForm.specs.length==1){
        return false
      } else{
        this.dataForm.specDisplayType = 0
        return true
      }
    }
  },
  watch: {
    "dataForm.serverType": {
      handler(val) {
        if (val == 3) {
          this.roleRules.deposit = { required: true, type: 'number', message: "请输入押金", trigger: "blur" }
        } else {
          this.$delete(this.roleRules, 'deposit')
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      immediate: true
    }
  },
  components: {
    UploadImg,
    GoodsSpec,
    RichEditor,
    UploadOssFile,
    ImageSelect
  },
  mounted() {
    this.init()
  },

  methods: {
    init() {
      if (this.$route.query.id) {
        this.dataForm.commonServerId = this.$route.query.id
        this.getData()
      }
      this.getTreeThreeServerList()
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getData() {
      CommonServerApi.getCommonServerInfo({
        id: this.dataForm.commonServerId
      }).then(res => {
        //if(res.data.sort==999)res.data.sort = ""
        let classifyIds = []
        if (res.data.serverClassifyId) classifyIds.push(res.data.serverClassifyId)
        if (res.data.thirdClassifyId) classifyIds.push(res.data.thirdClassifyId)
        // 处理规格列表
        res.data.commonServerVariants&&res.data.commonServerVariants.forEach(item=>item.moreImg = item.moreImg?item.moreImg.split(","):[])
        res.data.classifyIds = classifyIds
        this.fileList = JSON.parse(JSON.stringify(res.data.commonServerImages || []))
        this.$Utils.bindingBean(this.dataForm, res.data)
      })
    },
    getUrlList(val) {
      this.fileList = JSON.parse(JSON.stringify(this.dataForm.commonServerImages.concat(val)))
      this.showImageSelectDialog = false
    },
    getRichText(val) {
      this.dataForm.describes = val
    },
    // 获取上传的文件列表
    getImgVideo(val) {
      this.dataForm.commonServerImages = val
    },
    // 获取二三级服务列表
    getTreeThreeServerList() {
      let params = {
        level: 2,
      }
      ServerClassifyApi.listServerClassify(params).then(res => {
        this.treeThreeServerList = res.data
      })
    },
    handleFlagChange(val){
      const {visitFlag,shopFlag,remoteFlag} = this.dataForm
      switch(val){
        case 1:
          if(visitFlag){
            this.dataForm.shopFlag = 0
            this.dataForm.remoteFlag = 0
          }
          break
        case 2:
          if(shopFlag){
            this.dataForm.visitFlag = 0
            this.dataForm.remoteFlag = 0
          }
          break
        case 3:
        if(remoteFlag){
            this.dataForm.shopFlag = 0
            this.dataForm.visitFlag = 0
          }
          break
      }
    },
    checkData() {
      if (!this.$refs.goodsSpec.checkSpec()) return
      if(this.dataForm.dockingFlag==2&&!this.dataForm.dockingType){
        this.$message.error('对接类型不能为空')
        return false
      }

      if (this.dataForm.commonServerVariants.length) {
        this.dataForm.variantState = 2
        this.commonServerVariants = JSON.parse(JSON.stringify(this.dataForm.commonServerVariants))
        this.commonServerVariants.forEach(item=>item.moreImg=item.moreImg.join(","))
      } else {
        this.dataForm.variantState = 1
      }

      if (!this.dataForm.commonServerImages.some(item => item.type == 1)) {
        this.$message.error("请至少选择一张货品图片")
        return false
      }

      if (!this.dataForm.commonServerImages.some(item => item.type == 1 && item.mainFlag == 1)) {
        this.$message.error("请至少选择一张产品主图")
        return false
      }
      return true
    },

    async sureClick() {
      await Promise.all([this.$refs.dataForm.validate(),this.$refs.dataForm2.validate()])
      if(!this.checkData()) return
      await this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
      if (this.dataForm.commonServerId) {
        this.editData();
      } else {
        this.addData();
      }
      // this.$refs.dataForm.validate(valid => {
      //   if (valid) {
      //     if (!this.checkData()) return
      //     this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
      //       .then(() => {
      //         if (this.dataForm.commonServerId) {
      //           this.editData();
      //         } else {
      //           this.addData();
      //         }
      //       });
      //   }
      // })
    },
    // 商户原价改变
    handleMarketPriceBlur() {
      const { marketPrice, discount, costPrice } = this.dataForm
      if (costPrice && marketPrice && costPrice > marketPrice) {
        this.dataForm.marketPrice = ""
        this.dataForm.discount = ""
        this.$message.error("商户原价不能小于成本价")
        return
      }

      this.dataForm.costPrice = parseFloat((marketPrice * discount / 100).toFixed(4))
    },
    // 商户折扣比例改变
    handleDiscountBlur() {
      const { marketPrice, discount } = this.dataForm
      this.dataForm.costPrice = parseFloat((marketPrice * discount / 100).toFixed(4))
    },
    handleCostBlur() {
      const { costPrice, marketPrice } = this.dataForm
      if(costPrice==0){
        return
      }
      if (costPrice && marketPrice && costPrice > marketPrice) {
        this.dataForm.marketPrice = ""
        this.dataForm.discount = ""
        this.$message.error("成本价不能大于商户原价")
        return
      }
      this.dataForm.discount = parseFloat((costPrice / marketPrice*100).toFixed(2))
    },
    // 价格或者配送费改变,需要计算出售价
    handleMoneyChange() {
      let price = this.dataForm.price || 0
      let deliveryFee = this.dataForm.deliveryFee || 0
      this.dataForm.salePrice = parseFloat((price + deliveryFee).toFixed(2))
    },
    handleMoneyInput(flag) {
      if (!flag) {
        // 只保留两位小数
        this.dataForm.price = parseFloat(parseFloat(this.dataForm.price).toFixed(2))
        !this.dataForm.price ? this.dataForm.price = 0 : ""
      } else if (flag == 1) {
        this.dataForm.salePrice = parseFloat(parseFloat(this.dataForm.salePrice).toFixed(2))
        !this.dataForm.salePrice ? this.dataForm.salePrice = 0 : ""
      } else if (flag == 2) {
        // 只保留两位小数
        this.dataForm.costPrice = parseFloat(parseFloat(this.dataForm.costPrice).toFixed(4))
        !this.dataForm.costPrice ? this.dataForm.costPrice = 0 : ""
      } else if (flag == 3) {
        // 只保留两位小数
        this.dataForm.packageFee = parseFloat(parseFloat(this.dataForm.packageFee).toFixed(2))
        !this.dataForm.packageFee ? this.dataForm.packageFee = 0 : ""
      } else if (flag == 4) {
        // 只保留两位小数
        this.dataForm.deposit = parseFloat(parseFloat(this.dataForm.deposit).toFixed(2))
        !this.dataForm.deposit ? this.dataForm.deposit = 0 : ""
      } else if(flag==5){
        // 只保留两位小数
        this.dataForm.marketPrice = parseFloat(parseFloat(this.dataForm.marketPrice).toFixed(2))
        !this.dataForm.marketPrice ? this.dataForm.marketPrice = 0 : ""
      }
    },
    // 平台比例输入的时候
    handleDiscountInput() {
      this.dataForm.discount = parseFloat(parseFloat(this.dataForm.discount).toFixed(2))
      if (this.dataForm.discount && this.dataForm.discount > 99.72) {
        this.dataForm.discount = 0
        this.$message.error("商户折扣比例只能是0-99.72之间")
      } else if (this.dataForm.discount) {
        this.dataForm.discount = parseFloat(parseFloat(this.dataForm.discount).toFixed(2))
      } else {
        this.dataForm.discount = 0
      }
    },
    addData() {
      let param = {
        //sort: this.dataForm.sort ? this.dataForm.sort : 999,
        serverType: this.dataForm.serverType,
        deposit: this.dataForm.serverType == 3 ? this.dataForm.deposit : "",
        serverClassifyId: this.dataForm.classifyIds[0] ? this.dataForm.classifyIds[0] : "",
        thirdClassifyId: this.dataForm.classifyIds[1] ? this.dataForm.classifyIds[1] : "",
        name: this.dataForm.name,
        commonServerImages: this.dataForm.commonServerImages,
        describes: this.dataForm.describes,
        introduce: this.dataForm.introduce,
        businessConfirmWay:this.dataForm.businessConfirmWay,
        visitFlag: this.dataForm.visitFlag,
        shopFlag: this.dataForm.shopFlag,
        remoteFlag: this.dataForm.remoteFlag,
        fastFlag: this.dataForm.fastFlag,
        backFlag: this.dataForm.serverType == 3 ? this.dataForm.backFlag : "",
        deliveryFlag: this.dataForm.deliveryFlag,
        packageFlag: this.dataForm.packageFlag,
        price: this.dataForm.price,
        marketPrice:this.dataForm.marketPrice,
        discount:this.dataForm.discount,
        costPrice: this.dataForm.costPrice,
        salePrice: this.dataForm.salePrice,
        deliveryFee: this.dataForm.deliveryFee,
        packageFee: this.dataForm.packageFee,
        remark: this.dataForm.remark,
        specs: this.dataForm.specs,
        commonServerVariants: this.commonServerVariants,
        dockingType:this.dataForm.dockingType,
        dockingFlag:this.dataForm.dockingFlag,
        specDisplayType:this.dataForm.specDisplayType,
      };
      CommonServerApi.addCommonServer(param).then(res => {
        this.$Utils.notifySuccess()
        this.returnList();
      })
    },
    editData() {
      let param = {
        //sort:this.dataForm.sort?this.dataForm.sort:999,
        serverType: this.dataForm.serverType,
        deposit: this.dataForm.serverType == 3 ? this.dataForm.deposit : "",
        commonServerId: this.dataForm.commonServerId,
        serverClassifyId: this.dataForm.classifyIds[0] ? this.dataForm.classifyIds[0] : "",
        thirdClassifyId: this.dataForm.classifyIds[1] ? this.dataForm.classifyIds[1] : "",
        name: this.dataForm.name,
        commonServerImages: this.dataForm.commonServerImages,
        describes: this.dataForm.describes,
        introduce: this.dataForm.introduce,
        businessConfirmWay:this.dataForm.businessConfirmWay,
        visitFlag: this.dataForm.visitFlag,
        shopFlag: this.dataForm.shopFlag,
        remoteFlag: this.dataForm.remoteFlag,
        fastFlag: this.dataForm.fastFlag,
        backFlag: this.dataForm.serverType == 3 ? this.dataForm.backFlag : "",
        deliveryFlag: this.dataForm.deliveryFlag,
        packageFlag: this.dataForm.packageFlag,
        price: this.dataForm.price,
        costPrice: this.dataForm.costPrice,
        salePrice: this.dataForm.salePrice,
        marketPrice:this.dataForm.marketPrice,
        discount:this.dataForm.discount,
        deliveryFee: this.dataForm.deliveryFee,
        packageFee: this.dataForm.packageFee,
        remark: this.dataForm.remark,
        specs: this.dataForm.specs,
        commonServerVariants: this.commonServerVariants,
        commonServerCode: this.dataForm.commonServerCode,
        dockingType:this.dataForm.dockingType,
        dockingFlag:this.dataForm.dockingFlag,
        specDisplayType:this.dataForm.specDisplayType,
      };
      CommonServerApi.editCommonServer(param)
        .then(data => {
          this.$Utils.notifySuccess()
          this.returnList();
        })
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.push({ path: '/goods/commonServerManagement' });
    }
  },

}
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/serverAdd.scss";
</style>

<style lang="scss" scoped>
// .upload-img {
//   &::v-deep .el-upload-dragger {
//     display: flex;
//     justify-content: space-around;
//     align-items: center;

//     .tip {
//       padding-bottom: 30px;
//     }
//   }
// }
.flex-box {
  display: flex;
  align-items: center;

  &>div {
    margin-right: 10px;
  }

  .server-img {
    position: relative;
    font-size: 14px;

    .label {
      color: red;
      position: absolute;
      top: 0;
      left: -12px;
    }
  }
}

.introduce {
  margin-bottom: 10px;
  font-size: 14px;
  display: flex;
  width: 1000px;
  justify-content: space-between;

  .item {
    width: 46%;
    display: flex;
    text-align: end;

    .label {
      width: 80px;
      padding-right: 7px;
    }
  }

}
</style>
